import { Notification, dialog, BrowserWindow } from "electron";
import { exec } from "child_process";

export function showSystemNotice(data: { title: string; body: string }) {
  const notification = new Notification({
    ...data,
    icon: "icon.png",
  });
  notification.show();
}

export function setAlwaysOnTop(
  mainWindow: BrowserWindow | null,
  type: boolean,
) {
  mainWindow?.setAlwaysOnTop(type);
}

export function executeCommand(command: string) {
  exec(command, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing command: ${error.message}`);
      return;
    }
  });
}

export function shakeWindow(mainWindow: BrowserWindow | null) {
  if (!mainWindow) return;
  const bounds = mainWindow.getBounds();
  let xPos = bounds.x;
  let yPos = bounds.y;
  const shakeDistance = 5;
  const shakeTimes = 10;
  let i = 0;
  const interval = setInterval(() => {
    if (i >= shakeTimes) {
      clearInterval(interval);
      return;
    }
    xPos = i % 2 === 0 ? bounds.x + shakeDistance : bounds.x - shakeDistance;
    mainWindow.setBounds({
      x: xPos,
      y: yPos,
      width: bounds.width,
      height: bounds.height,
    });
    i++;
  }, 20);
}

export function windowOperation(
  mainWindow: BrowserWindow | null,
  type: string,
) {
  if (!mainWindow) return;
  switch (type) {
    case "minimize":
      mainWindow.minimize();
      break;
    case "maximize":
      mainWindow.maximize();
      break;
    case "restore":
      mainWindow.restore();
      break;
    default:
      mainWindow.close();
      break;
  }
}

export async function selectDirectory(): Promise<{
  status: number;
  data?: string;
}> {
  const result = await dialog.showOpenDialog({
    properties: ["openDirectory"],
  });
  if (!result.canceled) {
    console.log("选择的文件夹路径:", result.filePaths);
    return {
      status: 200,
      data: result.filePaths[0],
    };
  } else {
    console.log("没有选择文件夹");
    return {
      status: 400,
    };
  }
}
